package com.wisdytech.linkdcs.tool.action;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.StandardResult;
import com.wisdytech.common.bean.StandardTableResult;
import com.wisdytech.common.handler.ResourceMatchingService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.DateUtil;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.tool.model.TmProductModel;
import com.wisdytech.linkdcs.tool.model.TtEqTool;
import com.wisdytech.linkdcs.tool.service.ITtEqToolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhanghailin
 * @since 2018-06-05
 */
@Controller
@RequestMapping("/tool/toolInfo")
public class TtEqToolAction {

    @Value("${img.localtion}")
    private String fileLocation;

    @Resource
    private ITtEqToolService ttEqToolService;
    @Autowired
    @Qualifier("resourceMatchingService")
    private ResourceMatchingService resourceMatchingService;
    /**
     *
     * <p>Description: 设备信息</p>
     * @param model model
     * @return String
     */
    @RequestMapping("/index")
    public String toolInfoIndex(Model model, HttpServletRequest httpRequest){
        this.resourceMatchingService.getResourceName(httpRequest,model);
        return "tool/toolInfo";
    }

    @RequestMapping(value = "listToolInfoByFilter/get.mvc")
    @ResponseBody
    public StandardTableResult<TtEqTool> listToolInfoByFilter(String toolCode,String toolName,String opCode,String toolModel,String toolStatus, String maintainFlag,String checkoutFlag,Filter filter) {
        PageInfo<TtEqTool> page = ttEqToolService.listToolInfoByFilter(toolCode,toolName,toolModel,"",opCode,toolStatus,"","",maintainFlag,checkoutFlag,filter);
        return new StandardTableResult<>(page.getTotal(),page.getList());
    }

    /**
     * 保存/更新工装信息
     * @param ttEqTool 实体类
     * @return StandardResult
     */
    @RequestMapping(value = "/saveOrUpdateToolInfo/save.mvc")
    @ResponseBody
    public StandardResult saveOrUpdateToolInfo(TtEqTool ttEqTool) {
        SysUser user = BaseUtil.getCurrentUser();
        this.ttEqToolService.saveOrUpdateTool(ttEqTool,user);
        return StandardResult.getSuccessResult();
    }

    /**
     * 工装侧标栏列表
     * @param search 查询
     * @return StandardResult
     */
    @RequestMapping(value = "/getToolList/get.mvc")
    @ResponseBody
    public StandardResult getToolList(String search) {
        List<TtEqTool> list = this.ttEqToolService.getToolList(search);
        return StandardResult.getSuccessResult(list);
    }

    /**
     *
     * @param pkIds 主键
     * @return StandardResult
     */
    @RequestMapping(value = "/deleteToolById/del.mvc")
    @ResponseBody
    public StandardResult deleteToolById(String pkIds) {
        SysUser operator = BaseUtil.getCurrentUser();
        this.ttEqToolService.deleteTool(pkIds,operator);
        return StandardResult.getSuccessResult();
    }

    /**
     *
     * @param pkId 主键
     * @return StandardResult
     */
    @RequestMapping(value = "/getToolInfoById/get.mvc")
    @ResponseBody
    public StandardResult getToolInfoById(String pkId) {
        TtEqTool t = this.ttEqToolService.getToolInfoById(pkId);
        return StandardResult.getSuccessResult(t);
    }

    /**
     *
     * @param search 主键
     * @return StandardResult
     */
    @RequestMapping(value = "/findProductModel/get.mvc")
    @ResponseBody
    public StandardResult findProductModel(String search) {
        List<TmProductModel> t = this.ttEqToolService.findProductModel(search);
        return StandardResult.getSuccessResult(t);
    }

    /**
     * <p>Description: 保存设备对象</p>
     * @param file 上传的文件对象
     * @return 处理结果对象
     */
    @RequestMapping(value = "/batchImportToolInfo/save.mvc")
    @ResponseBody
    public StandardResult batchImportToolInfo(@RequestParam(value = "file", required = false) MultipartFile file) {
        if (file==null) {
            return StandardResult.getFailResult("文件上传失败");
        }
        SysUser operator = BaseUtil.getCurrentUser();
        this.ttEqToolService.batchImportToolInfo(file,operator);
        return StandardResult.getSuccessResult("数据导入成功",null);
    }

    /**
     * <p>Description: 保存设备对象</p>
     * @param file 设备对象
     * @param request 请求对象
     * @return 处理结果对象
     */
    @RequestMapping(value = "/uploadFile/save.mvc")
    @ResponseBody
    public JSONObject uploadFile(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
        if(!file.isEmpty()){
            //文件位置存放在tomcat webapp根目录
            //String rootPath = request.getSession().getServletContext().getRealPath("/")+"document/";
            String rootPath = fileLocation+"/tool/";
            String originalFilename = file.getOriginalFilename();
            //文件初始名
            String fileName = file.getOriginalFilename();
            //文件扩展名
            String extendName = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            //文件重命名
            String realName = BaseUtil.getUUID()+extendName;
            //文件夹名
            String dirName =  DateUtil.getCurDateDefaultStr()+"/";

            File targetFile = new File(rootPath+dirName, realName);

            if(!targetFile.getParentFile().exists()){
                targetFile.getParentFile().mkdirs();
            }
            //保存
            JSONObject result = new JSONObject();
            result.put("filePath", "tool/"+dirName+realName);
            result.put("originalFileName", originalFilename);
            //文件大小单位KB
            long fileSize = file.getSize()/1000;
            if(fileSize==0L) {
                fileSize = 1L;
            }
            result.put("fileSize", fileSize);
            result.put("fileName",realName);
            try {
                file.transferTo(targetFile);
                return result;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new JSONObject();
    }

    /**
     *
     * <p>Description: 下载文件</p>
     */
    @RequestMapping(value = "/downloadImportTemplate/get.mvc")
    //@ResponseBody
    public ResponseEntity<FileSystemResource> download() throws UnsupportedEncodingException {
        //String filename = URLEncoder.encode("工装保养项导入模板.xlsx", StandardCharsets.UTF_8.displayName());
        String filename = new String("工装信息导入模板.xlsx".getBytes("gb2312"),"ISO-8859-1");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + filename);
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        File file = null;
        try {
            file = ResourceUtils.getFile("classpath:static/excelTemplates/工装信息导入模板.xlsx");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }


    public static void main(String[] args) {
        System.out.println(BaseUtil.getUUID());
    }

}

